from haystack import indexes
from homeApp.models import Goods

class GoodsIndex(indexes.SearchIndex, indexes.Indexable):
    # 定义索引字段
    text = indexes.CharField(document=True, use_template=True)
    title = indexes.CharField(model_attr='title', boost=2.0)
    subtitle = indexes.CharField(model_attr='subtitle', null=True)
    description = indexes.CharField(model_attr='description', null=True)
    price = indexes.DecimalField(model_attr='price')
    original_price = indexes.DecimalField(model_attr='original_price', null=True)
    create_at = indexes.DateTimeField(model_attr='create_at')
    is_active = indexes.BooleanField(model_attr='is_active')
    
    def get_model(self):
        # 返回要索引的模型
        return Goods
    
    def index_queryset(self, using=None):
        # 返回要索引的数据，这里只索引激活的商品
        return self.get_model().objects.filter(is_active=True).order_by('-create_at')
    
    def prepare_text(self, obj):
        # 准备text字段的内容，用于全文搜索
        return f"{obj.title} {obj.subtitle or ''} {obj.description or ''}"